<?php
/**********************************************************************************
* SM-TestSuite.php                                                                *
***********************************************************************************
* Project Name: Test Suite                                                        *
* Written by: Joker™                                     						  *
***********************************************************************************
* This program is free software; you may redistribute it and/or modify it under   *
* the terms of the provided license as published by Simple Machines NPO.          *
*                                                                                 *
* This program is distributed in the hope that it is and will be useful, but      *
* WITHOUT ANY WARRANTIES; without even any implied warranty of MERCHANTABILITY    *
* or FITNESS FOR A PARTICULAR PURPOSE.                                            *
*                                                                                 *
* See the "license.txt" file for details of the Simple Machines license.          *
* The latest version can always be found at http://www.simplemachines.org.        *
***********************************************************************************
* Copyright 2011 SimpleMachines NPO - All Rights Reserved                         *
**********************************************************************************/

if (!defined('SMF'))
	die ('Hacking Attempt...');

function SMTestSuiteMain()
{
	global $context, $txt, $scripturl, $sourcedir, $settings;

	// Call CSS :P, which we have made with utmost love.
	$context['html_headers'] .= '<link rel="stylesheet" type="text/css" href="' . $settings['default_theme_url'] .  '/css/SM-TestSuite.css" />';

	// Load our template & language file.
	loadTemplate('SM-TestSuite');
	loadLanguage('SM-TestSuite');

	// Define a page title...
	$context['page_title'] = $txt['sm_testsuite'];

	// Add a link to the Christmas tree!
	$context['linktree'][] = array(
		'url' => $scripturl . '?action=testsuite',
		'name' => $txt['sm_testsuite'],
	);

	// Our Subs-File.
	require_once($sourcedir . '/Subs-SM-TestSuite.php');
	requestProjects();

	// Load a Project!
	if (isset($_GET['project']))
	{
		$final = (int) $_GET['project'];
		if (!empty($final))
		{
			loadProject($final);
		}
		else
		{
			fatal_error('Sorry, invalid characters were used in the URL.', false);
		}
	}
}

function loadProject($projectID)
{
	global $scripturl, $context, $sourcedir;

	// Make a note of Project ID and build a linktree for Project
	$context['test_suite']['current_project'] = $context['test_suite']['project'][$projectID];
	$context['page_title'] = $context['test_suite']['current_project']['name'];
	$context['linktree'][] = array(
		'url' => $scripturl . '?action=testsuite;project=' . $projectID,
		'name' => $context['test_suite']['current_project']['name'],
	);
	$context['sub_template'] = 'sm_testsuite_project_view';
	
	// Call all Suites associated to this Project
	requestTestSuites();
	
	if (isset($_GET['suite']))
	{
		$final = (int) $_GET['suite'];
		if (!empty($final))
		{
			loadSuites($final);
		}
		else
		{
			fatal_error('Sorry, invalid characters were used in the URL.', false);
		}
	}
}

function loadSuites($suiteID)
{
	global $scripturl, $context, $sourcedir, $sourcedir;

	$project_id = (int) $_REQUEST['project'];
	
	// Make a note of Suite ID and build a linktree for Suite
	$context['test_suite']['current_suite'] = $context['test_suite']['suite'][$suiteID];
	$context['page_title'] = $context['test_suite']['current_suite']['name'];
	$context['linktree'][] = array(
		'url' => $scripturl . '?action=testsuite;project=' . $project_id . ';suite=' . $suiteID,
		'name' => $context['test_suite']['current_suite']['name'],
	);
	$context['sub_template'] = 'sm_testsuite_case_view';
	
	// Call all Test Cases associated to this Suite
	requestTestCases();
		
	if (isset($_GET['case']))
	{
		$final = (int) $_GET['case'];
		if (!empty($final))
		{
			loadCases($final);
		}
		else
		{
			fatal_error('Sorry, invalid characters were used in the URL.', false);
		}
	}
}

function loadCases($caseID)
{
	global $scripturl, $context, $sourcedir , $sourcedir;

	$project_id = (int) $_REQUEST['project'];
	$suite_id = (int) $_REQUEST['suite'];

	// Make a note of Test Case ID & Run ID and build a linktree for Test Case
	$context['test_suite']['current_case'] = $context['test_suite']['case'][$caseID];
	$context['page_title'] = $context['test_suite']['current_case']['name'];
	$context['linktree'][] = array(
		'url' => $scripturl . '?action=testsuite;project=' . $project_id . ';suite=' . $suite_id . ';case=' . $caseID,
		'name' => $context['test_suite']['current_case']['name'],
	);
	$context['sub_template'] = 'sm_testsuite_separate_case_view';
	
	// Call all Runs associated to this Suite
	requestRuns();
	
	if (isset($_GET['run']))
	{
		$final = (int) $_GET['run'];
		if (!empty($final))
		{
			loadRuns($final);
		}
		else
		{
			fatal_error('Sorry, invalid characters were used in the URL.', false);
		}
	}	
}

function loadRuns($runID)
{
	global $scripturl, $context, $sourcedir, $sourcedir;

	$project_id = (int) $_REQUEST['project'];
	$suite_id = (int) $_REQUEST['suite'];
	$case_id = (int) $_REQUEST['case'];
	
	$context['test_suite']['current_run'] = $context['test_suite']['run'][$runID];
	$context['page_title'] = $context['test_suite']['current_run']['name'];
	$context['linktree'][] = array(
		'url' => $scripturl . '?action=testsuite;project=' . $project_id . ';suite=' . $suite_id . ';case=' . $case_id . ';#run=' . $runID,
		'name' => $context['test_suite']['current_run']['name'],
	);
	$context['sub_template'] = 'sm_testsuite_separate_case_view';
}

function CountLink()
{
	global $scripturl, $context, $txt, $sourcedir, $settings;


	// Call CSS :P, which we have made with utmost love.
	$context['html_headers'] .= '<link rel="stylesheet" type="text/css" href="' . $settings['default_theme_url'] .  '/css/SM-TestSuite.css" />';

	// Load our template & language file.
	loadTemplate('SM-TestSuite');
	loadLanguage('SM-TestSuite');
	
	require_once($sourcedir . '/Subs-SM-TestSuite.php');
	requestRunsforSuites();
	requestTestSuites();
	
	$project_id = (int) $_REQUEST['project'];
	$suite_id = (int) $_REQUEST['suite'];
	$context['test_suite']['current_suite'] = $context['test_suite']['suite'][$suite_id];

	$result = isset($_REQUEST['result']) ? strtolower($_REQUEST['result']) : '';

	$context['page_title'] = $result;
	$context['linktree'][] = array(
		'url' => $scripturl . '?action=testsuite;project=' . $project_id,
		'name' => $txt['back_to_project'],
	);
	$context['sub_template'] = 'sm_testsuite_count_link';
}

//creation of world (Projects and Suites):P
function Project()
{
	global $txt, $scripturl, $modSettings, $user_info, $context, $sourcedir, $smcFunc, $settings;

	$context['html_headers'] .= '<link rel="stylesheet" type="text/css" href="' . $settings['default_theme_url'] .  '/css/SM-TestSuite.css" />';

	// Call template and language files in advance, I HATE delays :P
	loadTemplate('SM-TestSuite');
	loadLanguage('SM-TestSuite');

	require_once($sourcedir . '/Subs-SM-TestSuite.php');
	
	// Get Project ID For suites
	$context['test_suite']['current_project'] = isset($_REQUEST['project']) ? (int) $_REQUEST['project'] : 0; 
	$project_id = $context['test_suite']['current_project'];

	if (empty($context['post_errors']))
	$context['post_errors'] = array();
				
	ProjectValidator();
	
	// Set the destination action for submission.
	$context['destination'] = 'createproject2';
	$context['submit_label'] = $txt['post'];

	if(empty($project_id))
	$context['page_title'] = $txt['start_new_project'];
	
	else
	$context['page_title'] = $txt['start_new_suite'];

	// Call Our Sub-Template.
	$context['sub_template'] = 'create_project';
	
	// Add a link to the Christmas tree!
	if(empty($project_id))
	$context['linktree'][] = array(
		'name' => '<em>' . $txt['create_project'] . '</em>',
	);
	
	else
	$context['linktree'][] = array(
		'url' => $scripturl . '?action=testsuite;project='. $project_id,
		'name' => $txt['project'],
		'extra_before' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav">' . $context['page_title'] . ' ( </strong></span>',
		'extra_after' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav"> )</strong></span>'
	);
}

function Project2()
{
	global $txt, $modSettings, $sourcedir, $context, $scripturl, $user_info, $smcFunc;

	loadLanguage('SM-TestSuite');
	require_once($sourcedir . '/Subs-SM-TestSuite.php');

	// Sneaking off, are we?
	if (empty($_POST))
		redirectexit($scripturl);

	// Get Project ID For suites
	$context['test_suite']['current_project'] = isset($_REQUEST['project']) ? (int) $_REQUEST['project'] : 0; 
	$project_id = $context['test_suite']['current_project'];

	// Prevent double submission of this form.
	checkSubmitOnce('check');

	// No errors as yet.
	$post_errors = array();

	// If the session has timed out, let the user re-submit their form.
	if (checkSession('project', '', false) != '')
		$post_errors[] = 'session_timeout';

	// Check the name and description coming.
	if (!isset($_POST['name']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['name'])) === '')
		$post_errors[] = 'no_name';
	if (!isset($_POST['description']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['description']), ENT_QUOTES) === '')
		$post_errors[] = 'no_description';
	elseif (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_POST['description']) > $modSettings['max_messageLength'])
		$post_errors[] = 'long_description';
	else
	{
		// Prepare the description a bit for some additional testing.
		$_POST['description'] = $smcFunc['htmlspecialchars']($_POST['description'], ENT_QUOTES);
	}

	// Any mistakes?
	if (!empty($post_errors))
	{
		loadLanguage('Errors');
		
		$context['post_error'] = array('description' => array());
		foreach ($post_errors as $post_error)
		{
			$context['post_error'][$post_error] = true;
			if ($post_error == 'long_description')
				$txt['error_' . $post_error] = sprintf($txt['error_' . $post_error], $modSettings['max_messageLength']);

			$context['post_error']['description'][] = $txt['error_' . $post_error];
		}

		return Project();
	}

	// At about this point, we're creating and that's that.
	ignore_user_abort(true);
	@set_time_limit(300);

	// Add special html entities to the Project Name, username and email.
	$_POST['name'] = strtr($smcFunc['htmlspecialchars']($_POST['name']), array("\r" => '', "\n" => '', "\t" => ''));
	$poster_name = htmlspecialchars($user_info['username']);
	$poster_email = htmlspecialchars($user_info['email']);

	// At this point, we want to make sure the Project Name isn't too long.
	if ($smcFunc['strlen']($_POST['name']) > 100)
		$_POST['name'] = $smcFunc['substr']($_POST['name'], 0, 100);

	// Collect all parameters for the creation of Project.
	if(empty($project_id))
	{
		$projectOption = array(
			'id' => empty($project) ? 0 : $project,
			'project_name' => $_POST['name'],
			'description' => $_POST['description'],
		);
		$posterOptions = array(
			'id' => $user_info['id'],
			'name' => $poster_name,
			'email' => $poster_email,
		);
		
		createProject($projectOption, $posterOptions);

		// Dut-dut-duh-duh-DUH-duh-dut-duh-duh!  *dances to the Final Fantasy Fanfare...*
		redirectexit('action=testsuite');
	}
	
	// Collect all parameters for the creation of Suite.
	else
	{
		$suiteOptions = array(
			'id' => empty($suite) ? 0 : $suite,
			'id_project' => empty($project_id) ? 0 : $project_id,
			'suite_name' => $_POST['name'],
			'description' => $_POST['description'],
		);
		$posterOptions = array(
			'id' => $user_info['id'],
			'name' => $poster_name,
			'email' => $poster_email,
		);
		
		createSuite($suiteOptions, $posterOptions);

		// Dut-dut-duh-duh-DUH-duh-dut-duh-duh!  *dances to the Final Fantasy Fanfare...*
		redirectexit('action=testsuite;project=' . $project_id);
	}
}

function EditProject()
{
	global $txt, $scripturl, $modSettings, $user_info, $context, $sourcedir, $smcFunc, $settings;

	$context['html_headers'] .= '<link rel="stylesheet" type="text/css" href="' . $settings['default_theme_url'] .  '/css/SM-TestSuite.css" />';

	$context['test_suite']['current_project'] = isset($_REQUEST['project']) ? (int) $_REQUEST['project'] : 0; 
	$project_id = $context['test_suite']['current_project'];
	
	$context['test_suite']['current_suite'] = isset($_REQUEST['suite']) ? (int) $_REQUEST['suite'] : 0; 
	$suite_id = $context['test_suite']['current_suite'];
	
	if(empty($project_id))
	return false;
	
	loadTemplate('SM-TestSuite');
	loadLanguage('SM-TestSuite');
	require_once($sourcedir . '/Subs-SM-TestSuite.php');	
	
	// Get data for this specific suite.
	if(!empty($suite_id))
	{
		$request = $smcFunc['db_query']('', '
				SELECT
					suite_name, description, id_member, poster_name, poster_time, poster_email, modified_by, modified_time
					FROM {db_prefix}testsuite_suites
					WHERE id_suite = {int:current_suite}
					AND id_project = {int:current_project}',
					array(
					'current_suite' => $suite_id,
					'current_project' => $project_id,
					'current_member' => $user_info['id'],
				)
			);
			
		if ($smcFunc['db_num_rows']($request) == 0)
			fatal_lang_error('no_suite', false);
		$row = $smcFunc['db_fetch_assoc']($request);
		$smcFunc['db_free_result']($request);

		$context['name'] = $row['suite_name'];
		$context['description'] = $row['description'];
	}
	
	// Get data for the project to be edited.
	else
	{
		$request = $smcFunc['db_query']('', '
			SELECT
				project_name, description, id_member, poster_name, poster_time, poster_email, modified_by, modified_time
				FROM {db_prefix}testsuite_projects
				WHERE id_project = {int:current_project}',
				array(
				'current_project' => $project_id,
				'current_member' => $user_info['id'],
			)
		);
		
		if ($smcFunc['db_num_rows']($request) == 0)
			fatal_lang_error('no_project', false);
		$row = $smcFunc['db_fetch_assoc']($request);
		$smcFunc['db_free_result']($request);

		$context['name'] = $row['project_name'];
		$context['description'] = $row['description'];
	}
	
	if (empty($context['post_errors']))
	$context['post_errors'] = array();
		
	ProjectValidator();

	// Set the destination action for submission.
	$context['destination'] = 'editproject2';
	$context['submit_label'] = $txt['post'];

	// Call Our Sub-Template.
	$context['sub_template'] = 'edit_project';
	
	if(!empty($suite_id))
	$context['page_title'] = $txt['edit'] . ' '. $txt['suite'];
	else
	$context['page_title'] = $txt['edit'] . ' '. $txt['project'];
	
	if(!empty($suite_id))
	$context['linktree'][] = array(
	'url' => $scripturl . '?action=testsuite;project='. $project_id,
	'name' => $txt['project'],
	'extra_before' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav">' . $context['page_title'] . ' ( </strong></span>',
	'extra_after' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav"> )</strong></span>'
	);
	
	else
	$context['linktree'][] = array(
	'url' => $scripturl . '?action=testsuite',
	'name' => $txt['sm_testsuite'],
	'extra_before' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav">' . $context['page_title'] . ' ( </strong></span>',
	'extra_after' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav"> )</strong></span>'
	);
}

function EditProject2()
{
	global $txt, $modSettings, $sourcedir, $context, $scripturl, $user_info, $smcFunc;

	loadLanguage('SM-TestSuite');
	require_once($sourcedir . '/Subs-SM-TestSuite.php');

	$context['test_suite']['current_project'] = isset($_REQUEST['project']) ? (int) $_REQUEST['project'] : 0; 
	$project_id = $context['test_suite']['current_project'];
	
	$context['test_suite']['current_suite'] = isset($_REQUEST['suite']) ? (int) $_REQUEST['suite'] : 0; 
	$suite_id = $context['test_suite']['current_suite'];
	
	// Prevent double submission of this form.
	checkSubmitOnce('check');

	// No errors as yet.
	$post_errors = array();

	// If the session has timed out, let the user re-submit their form.
	if (checkSession('editproject', '', false) != '')
		$post_errors[] = 'session_timeout';

	// Get data for this specific suite.
	if(!empty($suite_id))
	{
		$request = $smcFunc['db_query']('', '
				SELECT
					suite_name, description, id_member, poster_name, poster_time, poster_email, modified_by, modified_time
					FROM {db_prefix}testsuite_suites
					WHERE id_suite = {int:current_suite}
					AND id_project = {int:current_project}',
					array(
					'current_suite' => $suite_id,
					'current_project' => $project_id,
					'current_member' => $user_info['id'],
				)
			);
			
		if ($smcFunc['db_num_rows']($request) == 0)
			fatal_lang_error('no_suite', false);
		$row = $smcFunc['db_fetch_assoc']($request);
		$smcFunc['db_free_result']($request);
	}
	
	// Get data for the project to be edited.
	else
	{
		$request = $smcFunc['db_query']('', '
			SELECT
				project_name, description, id_member, poster_name, poster_time, poster_email, modified_by, modified_time
				FROM {db_prefix}testsuite_projects
				WHERE id_project = {int:current_project}',
				array(
				'current_project' => $project_id,
				'current_member' => $user_info['id'],
			)
		);
		
		if ($smcFunc['db_num_rows']($request) == 0)
			fatal_lang_error('no_project', false);
		$row = $smcFunc['db_fetch_assoc']($request);
		$smcFunc['db_free_result']($request);
	}
		
		
	// Check the name and description coming.
	if (!isset($_POST['name']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['name'])) === '')
		$post_errors[] = 'no_name';
	if (!isset($_POST['description']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['description']), ENT_QUOTES) === '')
		$post_errors[] = 'no_description';
	elseif (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_POST['description']) > $modSettings['max_messageLength'])
		$post_errors[] = 'long_description';
	else
	{
		// Prepare the description a bit for some additional testing.
		$_POST['description'] = $smcFunc['htmlspecialchars']($_POST['description'], ENT_QUOTES);
	}

	// Any mistakes?
	if (!empty($post_errors))
	{
		loadLanguage('Errors');
		
		$context['post_error'] = array('description' => array());
		foreach ($post_errors as $post_error)
		{
			$context['post_error'][$post_error] = true;
			if ($post_error == 'long_description')
				$txt['error_' . $post_error] = sprintf($txt['error_' . $post_error], $modSettings['max_messageLength']);

			$context['post_error']['description'][] = $txt['error_' . $post_error];
		}

		return EditProject();
	}

	// At about this point, we're creating and that's that.
	ignore_user_abort(true);
	@set_time_limit(300);

	// Add special html entities to the Project Name, username and email.
	$_POST['name'] = strtr($smcFunc['htmlspecialchars']($_POST['name']), array("\r" => '', "\n" => '', "\t" => ''));
	$poster_name = htmlspecialchars($user_info['username']);
	$poster_email = htmlspecialchars($user_info['email']);

	// At this point, we want to make sure the Project Name isn't too long.
	if ($smcFunc['strlen']($_POST['name']) > 100)
		$_POST['name'] = $smcFunc['substr']($_POST['name'], 0, 100);

	if(!empty($suite_id) && !empty($project_id))
	{
		$suiteOptions = array(
			'id' => empty($suite_id) ? 0 : $suite_id,
			'id_project' => empty($project_id) ? 0 : $project_id,
			'suite_name' => $_POST['name'],
			'description' => $_POST['description'],
		);
		$posterOptions = array();

		// Only consider marking as editing if they have edited the subject, message or icon.
		if ((isset($_POST['name']) && $_POST['name'] != $row['suite_name']) || (isset($_POST['description']) && $_POST['description'] != $row['description']))
		{
				$suiteOptions['modify_time'] = time();
				$suiteOptions['modified_by'] = $user_info['name'];
		}
		modifySuite($suiteOptions, $posterOptions);

		// If we didn't change anything this time but had before put back the old info.
		if (!isset($suiteOptions['modify_time']) && !empty($row['modified_time']))
		{
			$suiteOptions['modify_time'] = $row['modified_time'];
			$suiteOptions['modified_by'] = $row['modified_by'];
		}
		redirectexit('action=testsuite;project='. $project_id);
	}
	
	elseif(empty($suite_id) && !empty($project_id))
	{
		$projectOptions = array(
			'id' => empty($project_id) ? 0 : $project_id,
			'project_name' => $_POST['name'],
			'description' => $_POST['description'],
		);
		$posterOptions = array();

		// Only consider marking as editing if they have edited the subject, message or icon.
		if ((isset($_POST['name']) && $_POST['name'] != $row['project_name']) || (isset($_POST['description']) && $_POST['description'] != $row['description']))
		{
				$projectOptions['modify_time'] = time();
				$projectOptions['modified_by'] = $user_info['name'];
		}
		modifyProject($projectOptions, $posterOptions);

		// If we didn't change anything this time but had before put back the old info.
		if (!isset($projectOptions['modify_time']) && !empty($row['modified_time']))
		{
			$projectOptions['modify_time'] = $row['modified_time'];
			$projectOptions['modified_by'] = $row['modified_by'];
		}
		redirectexit('action=testsuite;');
	}
}

function ProjectValidator()
{
	global $context, $modSettings, $smcFunc, $txt;

	//Creating?
	if (isset($_POST['description']) || !empty($context['post_error']))
	{
		// Validate inputs.
		if (empty($context['post_error']))
		{
			if (htmltrim__recursive(htmlspecialchars__recursive($_POST['name'])) == '')
				$context['post_error']['no_name'] = true;
			if (htmltrim__recursive(htmlspecialchars__recursive($_POST['description'])) == '')
				$context['post_error']['no_description'] = true;
			if (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_POST['description']) > $modSettings['max_messageLength'])
				$context['post_error']['long_description'] = true;
		}
		else
		{
			if (!isset($_POST['name']))
				$_POST['name'] = '';
			if (!isset($_POST['description']))
				$_POST['description'] = '';
		}

		// Set up the inputs for the form.
		$name = strtr($smcFunc['htmlspecialchars']($_POST['name']), array("\r" => '', "\n" => '', "\t" => ''));
		$project_description = $smcFunc['htmlspecialchars']($_POST['description'], ENT_QUOTES);

		// Make sure the subject isn't too long - taking into account special characters.
		if ($smcFunc['strlen']($name) > 100)
			$name = $smcFunc['substr']($name, 0, 100);

		// Have we inadvertently trimmed off the subject of useful information?
		if ($smcFunc['htmltrim']($name) === '')
			$context['post_error']['no_name'] = true;

		// Any errors occurred?
		if (!empty($context['post_error']))
		{
			loadLanguage('Errors');

			$context['error_type'] = 'minor';

			$context['post_error']['description'] = array();
			foreach ($context['post_error'] as $post_error => $dummy)
			{
				if ($post_error == 'description')
					continue;

				if ($post_error == 'long_description')
					$txt['error_' . $post_error] = sprintf($txt['error_' . $post_error], $modSettings['max_messageLength']);

				$context['post_error']['description'][] = $txt['error_' . $post_error];

				$context['error_type'] = 'serious';
			}
		}
		$context['name'] = addcslashes($name, '"');
		$context['description'] = str_replace(array('"', '<', '>', '&nbsp;'), array('&quot;', '&lt;', '&gt;', ' '), $project_description);

		// No check is needed, since nothing is really posted.
		checkSubmitOnce('free');
	}
}

// Ok complete new functions to create Test Cases and Runs
function Cases()
{
	global $txt, $scripturl, $modSettings, $user_info, $context, $sourcedir, $smcFunc, $settings;

	// Lol get CSS as we made a few styling of own for aligning things around
	$context['html_headers'] .= '<link rel="stylesheet" type="text/css" href="' . $settings['default_theme_url'] .  '/css/SM-TestSuite.css" />';

	// Loady loady :P
	loadTemplate('SM-TestSuite');
	loadLanguage('SM-TestSuite');

	if (empty($context['post_errors']))
		$context['post_errors'] = array();

	// Get alllll id's coming through
	$context['test_suite']['current_project'] = isset($_REQUEST['project']) ? (int) $_REQUEST['project'] : 0; 
	$project_id = $context['test_suite']['current_project'];
	
	$context['test_suite']['current_suite'] = isset($_REQUEST['suite']) ? (int) $_REQUEST['suite'] : 0; 
	$suite_id = $context['test_suite']['current_suite'];
	
	if(!empty($_REQUEST['id_assigned']))
	{
			$id_assigned = (int) $_REQUEST['id_assigned'];
	}
	
	CaseValidator();
	
	// Set the destination action for submission.
	$context['destination'] = 'cases2';
	$context['submit_label'] = $txt['post'];
	
	// Create page titles and linktrees
	$context['page_title'] = $txt['start_new_case'];
	
	$context['linktree'][] = array(
	'url' => $scripturl . '?action=testsuite;project='. $project_id . ';suite='. $suite_id,
	'name' => $txt['suite'],
	'extra_before' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav">' . $context['page_title'] . ' ( </strong></span>',
	'extra_after' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav"> )</strong></span>'
	);
	
	// Make some more effort for BBC Codes used in Test Cases
	$context['use_smileys'] = true;

	require_once($sourcedir . '/Subs-SM-TestSuite.php');

	// Now create the editor.
	$editorOptions = array(
		'id' => 'message',
		'value' => $context['message'],
		'labels' => array(
			'post_button' => $context['submit_label'],
		),
		'height' => '150px',
		'width' => '80%',
	);
	editor_controller($editorOptions);
	
	$context['post_box_name'] = $editorOptions['id'];

	// Call Our Sub-Template.
	$context['sub_template'] = 'create_case';
}

function Cases2()
{
	global $txt, $modSettings, $sourcedir, $context, $scripturl, $user_info, $smcFunc;

	loadLanguage('SM-TestSuite');
	require_once($sourcedir . '/Subs-SM-TestSuite.php');
	require_once($sourcedir . '/Subs-Post.php');

	//Alpha to delta -- get every incoming id.
	$context['test_suite']['current_project'] = isset($_REQUEST['project']) ? (int) $_REQUEST['project'] : 0; 
	$project_id = $context['test_suite']['current_project'];
	
	$context['test_suite']['current_suite'] = isset($_REQUEST['suite']) ? (int) $_REQUEST['suite'] : 0; 
	$suite_id = $context['test_suite']['current_suite'];
	
	$id_assigned = isset($_REQUEST['id_assigned']) ? (int) $_REQUEST['id_assigned'] : 0; 

	// Prevent double submission of this form.
	checkSubmitOnce('check');

	// No errors as yet.
	$post_errors = array();

	// If the session has timed out, let the user re-submit their form.
	if (checkSession('cases', '', false) != '')
		$post_errors[] = 'session_timeout';

	// Check the name and message and steps for Cases.
	if (!isset($_POST['name']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['name'])) === '')
		$post_errors[] = 'no_name';
	if (!isset($_POST['message']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['message']), ENT_QUOTES) === '')
		$post_errors[] = 'no_message';
	if (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_POST['message']) > $modSettings['max_messageLength'])
		$post_errors[] = 'long_message';
	if (!isset($_POST['steps']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['steps']), ENT_QUOTES) === '')
		$post_errors[] = 'no_steps';
	if (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_POST['steps']) > $modSettings['max_messageLength'])
		$post_errors[] = 'long_message';
	else
	{
		// Prepare the message and steps a bit for some additional testing.
		$_POST['message'] = $smcFunc['htmlspecialchars']($_POST['message'], ENT_QUOTES);
		$_POST['steps'] = $smcFunc['htmlspecialchars']($_POST['steps'], ENT_QUOTES);
		
		// Let's see if there's still some content left without the tags.
		if ($smcFunc['htmltrim'](strip_tags(parse_bbc($_POST['message'], false), '<img>')) === '' && (!allowedTo('admin_forum') || strpos($_POST['message'], '[html]') === false))
			$post_errors[] = 'no_message';
	}

	// Any mistakes?
	if (!empty($post_errors))
	{
		loadLanguage('Errors');
		
		//Check message from Suite
		$context['post_error'] = array('message' => array());
		foreach ($post_errors as $post_error)
		{
			$context['post_error'][$post_error] = true;
			if ($post_error == 'long_message')
				$txt['error_' . $post_error] = sprintf($txt['error_' . $post_error], $modSettings['max_messageLength']);

			$context['post_error']['message'][] = $txt['error_' . $post_error];
		}
		
		//Check steps from Suite
		$context['post_error'] = array('steps' => array());
		foreach ($post_errors as $post_error)
		{
			$context['post_error'][$post_error] = true;
			if ($post_error == 'long_message')
				$txt['error_' . $post_error] = sprintf($txt['error_' . $post_error], $modSettings['max_messageLength']);

			$context['post_error']['steps'][] = $txt['error_' . $post_error];
		}
		return Cases();
	}

	// At about this point, we're posting and that's that.
	ignore_user_abort(true);
	@set_time_limit(300);

	// Add special html entities to the Test Case Name, username, email and expected result.
	$_POST['name'] = strtr($smcFunc['htmlspecialchars']($_POST['name']), array("\r" => '', "\n" => '', "\t" => ''));
	$poster_name = htmlspecialchars($user_info['username']);
	$poster_email = htmlspecialchars($user_info['email']);
	$_POST['expected_result'] = strtr($smcFunc['htmlspecialchars']($_POST['expected_result']), array("\r" => '', "\n" => '', "\t" => ''));

	// At this point, we want to make sure the name isn't too long.
	if ($smcFunc['strlen']($_POST['name']) > 100)
		$_POST['name'] = $smcFunc['substr']($_POST['name'], 0, 100);	

	// At this point, we want to make sure the name isn't too long.
	if ($smcFunc['strlen']($_POST['expected_result']) > 100)
		$_POST['expected_result'] = $smcFunc['substr']($_POST['expected_result'], 0, 100);
	
	// Collect all parameters for the creation of Test Cases.
	$caseOption = array(
		'id' => empty($case) ? 0 : $case,
		'id_suite' => empty($suite_id) ? 0 : $suite_id,
		'case_name' => $_POST['name'],
		'description' => $_POST['message'],
		'steps' => $_POST['steps'],
		'expected_result' => $_POST['expected_result'],
	);
	$posterOptions = array(
		'id' => $user_info['id'],
		'name' => $poster_name,
		'email' => $poster_email,
		'id_assigned' =>  empty($id_assigned) ? 0 : $id_assigned,
	);
	createCase($caseOption, $posterOptions);
	
	if (isset($caseOption['id']))
			$case = $caseOption['id'];

	// Dut-dut-duh-duh-DUH-duh-dut-duh-duh!  *dances to the Final Fantasy Fanfare...*
	redirectexit('action=testsuite;project=' . $project_id . ';suite=' . $suite_id);

}

function EditCase()
{
	global $txt, $scripturl, $modSettings, $user_info, $context, $sourcedir, $smcFunc, $settings;

	$context['html_headers'] .= '<link rel="stylesheet" type="text/css" href="' . $settings['default_theme_url'] .  '/css/SM-TestSuite.css" />';

	// Get alllll id's coming through
	$context['test_suite']['current_project'] = isset($_REQUEST['project']) ? (int) $_REQUEST['project'] : 0; 
	$project_id = $context['test_suite']['current_project'];
	
	$context['test_suite']['current_suite'] = isset($_REQUEST['suite']) ? (int) $_REQUEST['suite'] : 0; 
	$suite_id = $context['test_suite']['current_suite'];
	
	$context['test_suite']['current_case'] = isset($_REQUEST['case']) ? (int) $_REQUEST['case'] : 0; 
	$case_id = $context['test_suite']['current_case'];
	
	$id_assigned = isset($_REQUEST['id_assigned']) ? (int) $_REQUEST['id_assigned'] : 0; 

	if(empty($project_id) && empty($suite_id))
	return false;
	
	loadTemplate('SM-TestSuite');
	loadLanguage('SM-TestSuite');
	require_once($sourcedir . '/Subs-SM-TestSuite.php');

	// Get data for this specific case.
	if(!empty($case_id))
	{
		$request = $smcFunc['db_query']('', '
				SELECT
					c.case_name, c.description, c.steps, c.expected_result, c.id_member, c.poster_name, c.poster_time, c.poster_email, c.id_assigned, c.modified_by, c.modified_time
					FROM {db_prefix}testsuite_cases AS c
					INNER JOIN {db_prefix}testsuite_projects AS p ON (p.id_project = {int:current_project})
					WHERE c.id_case = {int:current_case}
					AND c.id_suite = {int:current_suite}',
					array(
					'current_case' => $case_id,
					'current_suite' => $suite_id,
					'current_project' => $project_id,
					'current_member' => $user_info['id'],
				)
			);
			
		if ($smcFunc['db_num_rows']($request) == 0)
			fatal_lang_error('no_case', false);
		$row = $smcFunc['db_fetch_assoc']($request);
		$smcFunc['db_free_result']($request);

		$context['name'] = $row['case_name'];
		$context['message'] = $row['description'];
		$context['steps'] = $row['steps'];
		$context['expected_result'] = $row['expected_result'];
		$context['id_assigned'] = $row['id_assigned'];	
	}
	
		
	if (empty($context['post_errors']))
	$context['post_errors'] = array();
		
	CaseValidator();

	// Set the destination action for submission.
	$context['destination'] = 'editcase2';
	$context['submit_label'] = $txt['post'];

	$context['page_title'] = $txt['edit'] . ' '. $txt['case'];

	$context['linktree'][] = array(
	'url' => $scripturl . '?action=testsuite;project=' . $project_id . ';suite=' . $suite_id,
	'name' => $txt['suite'],
	'extra_before' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav">' . $context['page_title'] . ' ( </strong></span>',
	'extra_after' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav"> )</strong></span>'
	);
	
	// Call Our Sub-Template.
	$context['sub_template'] = 'edit_case';
	
	// Make some more effort for BBC Codes used in Test Cases
	$context['use_smileys'] = true;

	// Now create the editor.
	$editorOptions = array(
		'id' => 'message',
		'value' => $context['message'],
		'labels' => array(
			'post_button' => $context['submit_label'],
		),
		'height' => '150px',
		'width' => '80%',
	);
	editor_controller($editorOptions);
	
	$context['post_box_name'] = $editorOptions['id'];
}

function EditCase2()
{
	global $txt, $modSettings, $sourcedir, $context, $scripturl, $user_info, $smcFunc;

	loadLanguage('SM-TestSuite');
	require_once($sourcedir . '/Subs-SM-TestSuite.php');
	require_once($sourcedir . '/Subs-Post.php');

	$context['test_suite']['current_project'] = isset($_REQUEST['project']) ? (int) $_REQUEST['project'] : 0; 
	$project_id = $context['test_suite']['current_project'];
	
	$context['test_suite']['current_suite'] = isset($_REQUEST['suite']) ? (int) $_REQUEST['suite'] : 0; 
	$suite_id = $context['test_suite']['current_suite'];
	
	$context['test_suite']['current_case'] = isset($_REQUEST['case']) ? (int) $_REQUEST['case'] : 0; 
	$case_id = $context['test_suite']['current_case'];
	
	$id_assigned = isset($_REQUEST['id_assigned']) ? (int) $_REQUEST['id_assigned'] : 0;

	// Prevent double submission of this form.
	checkSubmitOnce('check');

	// No errors as yet.
	$post_errors = array();

	// If the session has timed out, let the user re-submit their form.
	if (checkSession('editcase', '', false) != '')
		$post_errors[] = 'session_timeout';

	if(!empty($case_id))
	{
		$request = $smcFunc['db_query']('', '
				SELECT
					c.case_name, c.description, c.steps, c.expected_result, c.id_member, c.poster_name, c.poster_time, c.poster_email, c.id_assigned, c.modified_by, c.modified_time
					FROM {db_prefix}testsuite_cases AS c
					INNER JOIN {db_prefix}testsuite_projects AS p ON (p.id_project = {int:current_project})
					WHERE c.id_case = {int:current_case}
					AND c.id_suite = {int:current_suite}',
					array(
					'current_case' => $case_id,
					'current_suite' => $suite_id,
					'current_project' => $project_id,
					'current_member' => $user_info['id'],
				)
			);
			
		if ($smcFunc['db_num_rows']($request) == 0)
			fatal_lang_error('no_case', false);
		$row = $smcFunc['db_fetch_assoc']($request);
		$smcFunc['db_free_result']($request);
	}
	
	// Check the name and message and steps for Cases.
	if (!isset($_POST['name']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['name'])) === '')
		$post_errors[] = 'no_name';
	if (!isset($_POST['message']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['message']), ENT_QUOTES) === '')
		$post_errors[] = 'no_message';
	if (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_POST['message']) > $modSettings['max_messageLength'])
		$post_errors[] = 'long_message';
	if (!isset($_POST['steps']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['steps']), ENT_QUOTES) === '')
		$post_errors[] = 'no_steps';
	if (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_POST['steps']) > $modSettings['max_messageLength'])
		$post_errors[] = 'long_message';
	else
	{
		// Prepare the message and steps a bit for some additional testing.
		$_POST['message'] = $smcFunc['htmlspecialchars']($_POST['message'], ENT_QUOTES);
		$_POST['steps'] = $smcFunc['htmlspecialchars']($_POST['steps'], ENT_QUOTES);
		
		// Let's see if there's still some content left without the tags.
		if ($smcFunc['htmltrim'](strip_tags(parse_bbc($_POST['message'], false), '<img>')) === '' && (!allowedTo('admin_forum') || strpos($_POST['message'], '[html]') === false))
			$post_errors[] = 'no_message';
	}

	// Any mistakes?
	if (!empty($post_errors))
	{
		loadLanguage('Errors');
		
		//Check message from Suite
		$context['post_error'] = array('message' => array());
		foreach ($post_errors as $post_error)
		{
			$context['post_error'][$post_error] = true;
			if ($post_error == 'long_message')
				$txt['error_' . $post_error] = sprintf($txt['error_' . $post_error], $modSettings['max_messageLength']);

			$context['post_error']['message'][] = $txt['error_' . $post_error];
		}
		
		//Check steps from Suite
		$context['post_error'] = array('steps' => array());
		foreach ($post_errors as $post_error)
		{
			$context['post_error'][$post_error] = true;
			if ($post_error == 'long_message')
				$txt['error_' . $post_error] = sprintf($txt['error_' . $post_error], $modSettings['max_messageLength']);

			$context['post_error']['steps'][] = $txt['error_' . $post_error];
		}
		return EditCase();
	}

	// At about this point, we're posting and that's that.
	ignore_user_abort(true);
	@set_time_limit(300);

	// Add special html entities to the Test Case Name, username, email and expected result.
	$_POST['name'] = strtr($smcFunc['htmlspecialchars']($_POST['name']), array("\r" => '', "\n" => '', "\t" => ''));
	$poster_name = htmlspecialchars($user_info['username']);
	$poster_email = htmlspecialchars($user_info['email']);
	$_POST['expected_result'] = strtr($smcFunc['htmlspecialchars']($_POST['expected_result']), array("\r" => '', "\n" => '', "\t" => ''));

	// At this point, we want to make sure the name isn't too long.
	if ($smcFunc['strlen']($_POST['name']) > 100)
		$_POST['name'] = $smcFunc['substr']($_POST['name'], 0, 100);	

	// At this point, we want to make sure the name isn't too long.
	if ($smcFunc['strlen']($_POST['expected_result']) > 100)
		$_POST['expected_result'] = $smcFunc['substr']($_POST['expected_result'], 0, 100);
	
	$caseOptions = array(
		'id' => empty($case_id) ? 0 : $case_id,
		'id_suite' => empty($suite_id) ? 0 : $suite_id,
		'case_name' => $_POST['name'],
		'description' => $_POST['message'],
		'steps' => $_POST['steps'],
		'expected_result' => $_POST['expected_result'],
	);
	$posterOptions = array(
			'id_assigned' =>  empty($id_assigned) ? 0 : $id_assigned,
);

	// Only consider marking as editing if they have edited the subject, message or icon.
	if ((isset($_POST['name']) && $_POST['name'] != $row['case_name']) || (isset($_POST['message']) && $_POST['message'] != $row['description']) || (isset($_POST['steps']) && $_POST['steps'] != $row['steps']) || (isset($_POST['expected_result']) && $_POST['expected_result'] != $row['expected_result']))
	{
			$caseOptions['modify_time'] = time();
			$caseOptions['modified_by'] = $user_info['name'];
	}
	modifyCase($caseOptions, $posterOptions);

	// If we didn't change anything this time but had before put back the old info.
	if (!isset($caseOptions['modify_time']) && !empty($row['modified_time']))
	{
		$caseOptions['modify_time'] = $row['modified_time'];
		$caseOptions['modified_by'] = $row['modified_by'];
	}
	redirectexit('action=testsuite;project='. $project_id .';suite='. $suite_id);
}

function CaseValidator()
{
	global $context, $modSettings, $smcFunc, $txt, $sourcedir;
	
	// Creating Suite, nope, first we are going to check it :D
	if (isset($_POST['message']) || isset($_POST['steps']) || !empty($context['post_error']))
	{
		// Validate inputs.
		if (empty($context['post_error']))
		{
			if (htmltrim__recursive(htmlspecialchars__recursive($_REQUEST['name'])) == '')
				$context['post_error']['no_name'] = true;
			if (htmltrim__recursive(htmlspecialchars__recursive($_REQUEST['message'])) == '')
				$context['post_error']['no_message'] = true;
			if (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_REQUEST['message']) > $modSettings['max_messageLength'])
				$context['post_error']['long_message'] = true;
			if (htmltrim__recursive(htmlspecialchars__recursive($_REQUEST['steps'])) == '')
				$context['post_error']['no_steps'] = true;
			if (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_REQUEST['steps']) > $modSettings['max_messageLength'])
				$context['post_error']['long_message'] = true;
		}
		else
		{
			if (!isset($_REQUEST['name']))
				$_REQUEST['name'] = '';
			if (!isset($_REQUEST['message']))
				$_REQUEST['message'] = '';
			if (!isset($_REQUEST['steps']))
				$_REQUEST['steps'] = '';
		}

		// Set up the inputs for the form.
		$name = strtr($smcFunc['htmlspecialchars']($_REQUEST['name']), array("\r" => '', "\n" => '', "\t" => ''));
		$message = $smcFunc['htmlspecialchars']($_POST['message'], ENT_QUOTES);
		$step = $smcFunc['htmlspecialchars']($_REQUEST['steps'], ENT_QUOTES);
		$expected_result = strtr($smcFunc['htmlspecialchars']($_REQUEST['expected_result']), array("\r" => '', "\n" => '', "\t" => ''));

		// Make sure the name and expected result isn't too long - taking into account special characters.
		if ($smcFunc['strlen']($name) > 100)
			$name = $smcFunc['substr']($name, 0, 100);
			
		if ($smcFunc['strlen']($expected_result) > 100)
			$expected_result = $smcFunc['substr']($expected_result, 0, 100);

		// Have we inadvertently trimmed off the name of useful information?
		if ($smcFunc['htmltrim']($name) === '')
			$context['post_error']['no_name'] = true;

		// Any errors occurred?
		if (!empty($context['post_error']))
		{
			loadLanguage('Errors');

			$context['error_type'] = 'minor';

			$context['post_error']['message'] = array();
			foreach ($context['post_error'] as $post_error => $dummy)
			{
				if ($post_error == 'message')
					continue;

				if ($post_error == 'long_message')
					$txt['error_' . $post_error] = sprintf($txt['error_' . $post_error], $modSettings['max_messageLength']);

				$context['post_error']['message'][] = $txt['error_' . $post_error];

				$context['error_type'] = 'serious';
			}
			
			$context['post_error']['steps'] = array();
			foreach ($context['post_error'] as $post_error => $dummy)
			{
				if ($post_error == 'steps')
					continue;

				if ($post_error == 'long_message')
					$txt['error_' . $post_error] = sprintf($txt['error_' . $post_error], $modSettings['max_messageLength']);

				$context['post_error']['steps'][] = $txt['error_' . $post_error];

				$context['error_type'] = 'serious';
			}
		}

		$context['name'] = addcslashes($name, '"');
		$context['message'] = str_replace(array('"', '<', '>', '&nbsp;'), array('&quot;', '&lt;', '&gt;', ' '), $message);
		$context['steps'] = str_replace(array('"', '<', '>', '&nbsp;'), array('&quot;', '&lt;', '&gt;', ' '), $step);
		$context['expected_result'] = addcslashes($expected_result, '"');
		if(!empty($id_assigned))
		$context['id_assigned'] = $id_assigned;
		
		// No check is needed, since nothing is really posted.
		checkSubmitOnce('free');
	}
}

function Run()
{
	global $txt, $scripturl, $modSettings, $user_info, $context, $sourcedir, $smcFunc, $settings;

	// Lol get CSS as we made a few styling of own for aligning things around
	$context['html_headers'] .= '<link rel="stylesheet" type="text/css" href="' . $settings['default_theme_url'] .  '/css/SM-TestSuite.css" />';

	// Loady loady :P
	loadTemplate('SM-TestSuite');
	loadLanguage('SM-TestSuite');
	require_once($sourcedir . '/Subs-SM-TestSuite.php');

	if (empty($context['post_errors']))
		$context['post_errors'] = array();

	// Get alllll id's coming through
	$context['test_suite']['current_project'] = isset($_REQUEST['project']) ? (int) $_REQUEST['project'] : 0; 
	$project_id = $context['test_suite']['current_project'];
	
	$context['test_suite']['current_suite'] = isset($_REQUEST['suite']) ? (int) $_REQUEST['suite'] : 0; 
	$suite_id = $context['test_suite']['current_suite'];
	
	$context['test_suite']['current_case'] = isset($_REQUEST['case']) ? (int) $_REQUEST['case'] : 0;
	$case_id = $context['test_suite']['current_case'];
	
	$id_bug = isset($_REQUEST['id_bug']) ? (int) $_REQUEST['id_bug'] : 0;

	RunValidator();
	
	// Set the destination action for submission.
	$context['destination'] = 'createrun2';
	$context['submit_label'] = $txt['post'];

	// Create page titles and linktrees
		$context['page_title'] = $txt['submit_run_result'];
		$context['linktree'][] = array(
			'url' => $scripturl . '?action=testsuite;project='. $project_id . ';suite='. $suite_id . ';case='. $case_id,
			'name' => $txt['case'],
			'extra_before' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav">' . $context['page_title'] . ' ( </strong></span>',
			'extra_after' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav"> )</strong></span>'
		);
		
	// Call Our Sub-Template.
	$context['sub_template'] = 'create_run';

}

function Run2()
{
	global $txt, $modSettings, $sourcedir, $context, $scripturl, $user_info, $smcFunc;

	loadLanguage('SM-TestSuite');
	require_once($sourcedir . '/Subs-SM-TestSuite.php');

	$context['test_suite']['current_project'] = isset($_REQUEST['project']) ? (int) $_REQUEST['project'] : 0; 
	$project_id = $context['test_suite']['current_project'];
	
	$context['test_suite']['current_suite'] = isset($_REQUEST['suite']) ? (int) $_REQUEST['suite'] : 0; 
	$suite_id = $context['test_suite']['current_suite'];
	
	$context['test_suite']['current_case'] = isset($_REQUEST['case']) ? (int) $_REQUEST['case'] : 0;
	$case_id = $context['test_suite']['current_case'];
	
	$id_bug = isset($_REQUEST['id_bug']) ? (int) $_REQUEST['id_bug'] : 0;
	
	// Prevent double submission of this form.
	checkSubmitOnce('check');

	// No errors as yet.
	$post_errors = array();

	// If the session has timed out, let the user re-submit their form.
	if (checkSession('createrun', '', false) != '')
		$post_errors[] = 'session_timeout';

	if($_POST['result'] == 'select')
			$post_errors[] = 'no_result';
	if (!isset($_POST['feedback']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['feedback']), ENT_QUOTES) === '')
		$post_errors[] = 'no_feedback';
	else
	{
		// Prepare the feedback a bit for some additional testing.
		$_POST['feedback'] = $smcFunc['htmlspecialchars']($_POST['feedback'], ENT_QUOTES);
	}
	
	// Any mistakes?
	if (!empty($post_errors))
	{
		loadLanguage('Errors');
		
		$context['post_error'] = array('feedback' => array());
		foreach ($post_errors as $post_error)
		{
			$context['post_error'][$post_error] = true;
			if ($post_error == 'long_feedback')
				$txt['error_' . $post_error] = sprintf($txt['error_' . $post_error], $modSettings['max_messageLength']);

			$context['post_error']['feedback'][] = $txt['error_' . $post_error];
		}
		
		return Run();
	}

	// At about this point, we're posting and that's that.
	ignore_user_abort(true);
	@set_time_limit(300);

	// Add special html entities to the Test Case Name, username, email and expected result.
	$poster_name = htmlspecialchars($user_info['username']);
	$poster_email = htmlspecialchars($user_info['email']);

	$runOption = array(
		'id' => empty($run) ? 0 : $run,
		'id_case' => empty($case_id) ? 0 : $case_id,
		'result_achieved' => $_POST['result'],
		'feedback' => $_POST['feedback'],
		'id_bug' => empty($id_bug) ? 0 : $id_bug,
	);
	$posterOptions = array(
		'id' => $user_info['id'],
		'name' => $poster_name,
		'email' => $poster_email,
	);
	createRun($runOption, $posterOptions);
	
	// Update the counter for total no of runs made in suites table
	$request = $smcFunc['db_query']('', '
			UPDATE {db_prefix}testsuite_suites
			SET count = count + {int:count}
			WHERE id_suite = {int:id_suite}',
				array(
					'id_suite' => $suite_id,
					'count' => 1,
				)
	);
	$smcFunc['db_free_result']($request);
				
	// Update the counter for no. of fail runs made in suites table
	if($_POST['result'] == 'fail')
	{
		$request = $smcFunc['db_query']('', '
			UPDATE {db_prefix}testsuite_suites
			SET fail_count = fail_count + {int:fail_count}
			WHERE id_suite = {int:id_suite}',
				array(
					'id_suite' => $suite_id,
					'fail_count' => 1,
			)
		);
		$smcFunc['db_free_result']($request);
	}

	// Update the counter for total no of runs made in cases table
	$request = $smcFunc['db_query']('', '
			UPDATE {db_prefix}testsuite_cases
			SET count = count + {int:count}
			WHERE id_case = {int:id_case}',
				array(
					'id_case' => $case_id,
					'count' => 1,
				)
	);
	$smcFunc['db_free_result']($request);
		
	// Update the counter for no. of fail runs made in cases table
	if($_POST['result'] == 'fail')
	{
		$request = $smcFunc['db_query']('', '
			UPDATE {db_prefix}testsuite_cases
			SET fail_count = fail_count + {int:fail_count}
			WHERE id_case = {int:id_case}',
				array(
					'id_case' => $case_id,
					'fail_count' => 1,
			)
		);
		$smcFunc['db_free_result']($request);
	}
  
	// Dut-dut-duh-duh-DUH-duh-dut-duh-duh!  *dances to the Final Fantasy Fanfare...*
	redirectexit('action=testsuite;project=' . $project_id . ';suite=' . $suite_id . ';case=' . $case_id);

}

function EditRun()
{
	global $txt, $scripturl, $modSettings, $user_info, $context, $sourcedir, $smcFunc, $settings;

	$context['html_headers'] .= '<link rel="stylesheet" type="text/css" href="' . $settings['default_theme_url'] .  '/css/SM-TestSuite.css" />';

	$context['test_suite']['current_project'] = isset($_REQUEST['project']) ? (int) $_REQUEST['project'] : 0; 
	$project_id = $context['test_suite']['current_project'];
	
	$context['test_suite']['current_suite'] = isset($_REQUEST['suite']) ? (int) $_REQUEST['suite'] : 0; 
	$suite_id = $context['test_suite']['current_suite'];
	
	$context['test_suite']['current_case'] = isset($_REQUEST['case']) ? (int) $_REQUEST['case'] : 0;
	$case_id = $context['test_suite']['current_case'];
	
	$context['test_suite']['current_run'] = isset($_REQUEST['run']) ? (int) $_REQUEST['run'] : 0;
	$run_id = $context['test_suite']['current_run'];
	
	$id_bug = isset($_REQUEST['id_bug']) ? (int) $_REQUEST['id_bug'] : 0;
	
	if(empty($project_id))
	return false;
	
	loadTemplate('SM-TestSuite');
	loadLanguage('SM-TestSuite');
	require_once($sourcedir . '/Subs-SM-TestSuite.php');	
	
	// Get data for this specific suite.
	if(!empty($run_id))
	{
		$request = $smcFunc['db_query']('', '
				SELECT
					r.result_achieved, r.feedback, r.id_bug, r.id_member, r.poster_name, r.poster_time, r.poster_email, r.modified_by, r.modified_time
					FROM {db_prefix}testsuite_runs AS r
					INNER JOIN {db_prefix}testsuite_suites AS s ON (s.id_suite = {int:current_suite})
					INNER JOIN {db_prefix}testsuite_projects AS p ON (p.id_project = {int:current_project})
					WHERE r.id_run = {int:current_run}
					AND r.id_case = {int:current_case}',
					array(
					'current_run' => $run_id,
					'current_case' => $case_id,
					'current_suite' => $suite_id,
					'current_project' => $project_id,
					'current_member' => $user_info['id'],
				)
			);
			
		if ($smcFunc['db_num_rows']($request) == 0)
			fatal_lang_error('no_run', false);
		$row = $smcFunc['db_fetch_assoc']($request);
		$smcFunc['db_free_result']($request);

		$context['result_achieved'] = $row['result_achieved'];
		$context['feedback'] = $row['feedback'];
		$context['id_bug'] = $row['id_bug'];
	}

	if (empty($context['post_errors']))
	$context['post_errors'] = array();
		
	RunValidator();

	// Set the destination action for submission.
	$context['destination'] = 'editrun2';
	$context['submit_label'] = $txt['post'];

	// Call Our Sub-Template.
	$context['sub_template'] = 'edit_run';
	
	$context['page_title'] = $txt['edit'] . ' '. $txt['run'];
	
	$context['linktree'][] = array(
	'url' => $scripturl . '?action=testsuite;project=' . $project_id . ';suite=' . $suite_id . ';case=' . $case_id,
	'name' => $txt['case'],
	'extra_before' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav">' . $context['page_title'] . ' ( </strong></span>',
	'extra_after' => '<span' . ($settings['linktree_inline'] ? ' class="smalltext"' : '') . '><strong class="nav"> )</strong></span>'
	);
}

function EditRun2()
{
	global $txt, $modSettings, $sourcedir, $context, $scripturl, $user_info, $smcFunc;

	loadLanguage('SM-TestSuite');
	require_once($sourcedir . '/Subs-SM-TestSuite.php');

	$context['test_suite']['current_project'] = isset($_REQUEST['project']) ? (int) $_REQUEST['project'] : 0; 
	$project_id = $context['test_suite']['current_project'];
	
	$context['test_suite']['current_suite'] = isset($_REQUEST['suite']) ? (int) $_REQUEST['suite'] : 0; 
	$suite_id = $context['test_suite']['current_suite'];
	
	$context['test_suite']['current_case'] = isset($_REQUEST['case']) ? (int) $_REQUEST['case'] : 0;
	$case_id = $context['test_suite']['current_case'];
	
	$context['test_suite']['current_run'] = isset($_REQUEST['run']) ? (int) $_REQUEST['run'] : 0;
	$run_id = $context['test_suite']['current_run'];
	
	$id_bug = isset($_REQUEST['id_bug']) ? (int) $_REQUEST['id_bug'] : 0;
	
	// Prevent double submission of this form.
	checkSubmitOnce('check');

	// No errors as yet.
	$post_errors = array();

	// If the session has timed out, let the user re-submit their form.
	if (checkSession('editrun', '', false) != '')
		$post_errors[] = 'session_timeout';

	// Get data for this specific run.
	$request = $smcFunc['db_query']('', '
				SELECT
					r.result_achieved, r.feedback, r.id_bug, r.id_member, r.poster_name, r.poster_time, r.poster_email, r.modified_by, r.modified_time
					FROM {db_prefix}testsuite_runs AS r
					INNER JOIN {db_prefix}testsuite_suites AS s ON (s.id_suite = {int:current_suite})
					INNER JOIN {db_prefix}testsuite_projects AS p ON (p.id_project = {int:current_project})
					WHERE r.id_run = {int:current_run}
					AND r.id_case = {int:current_case}',
					array(
					'current_run' => $run_id,
					'current_case' => $case_id,
					'current_suite' => $suite_id,
					'current_project' => $project_id,
					'current_member' => $user_info['id'],
				)
			);
			
		if ($smcFunc['db_num_rows']($request) == 0)
			fatal_lang_error('no_run', false);
		$row = $smcFunc['db_fetch_assoc']($request);
		$smcFunc['db_free_result']($request);		
		
	// If the session has timed out, let the user re-submit their form.
	if (checkSession('createrun', '', false) != '')
		$post_errors[] = 'session_timeout';

	if($_POST['result'] == 'select')
			$post_errors[] = 'no_result';
	if (!isset($_POST['feedback']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['feedback']), ENT_QUOTES) === '')
		$post_errors[] = 'no_feedback';
	else
	{
		// Prepare the feedback a bit for some additional testing.
		$_POST['feedback'] = $smcFunc['htmlspecialchars']($_POST['feedback'], ENT_QUOTES);
	}
	
	// Any mistakes?
	if (!empty($post_errors))
	{
		loadLanguage('Errors');
		
		$context['post_error'] = array('feedback' => array());
		foreach ($post_errors as $post_error)
		{
			$context['post_error'][$post_error] = true;
			if ($post_error == 'long_feedback')
				$txt['error_' . $post_error] = sprintf($txt['error_' . $post_error], $modSettings['max_messageLength']);

			$context['post_error']['feedback'][] = $txt['error_' . $post_error];
		}
		
		return EditRun();
	}

	// At about this point, we're posting and that's that.
	ignore_user_abort(true);
	@set_time_limit(300);

	// Add special html entities to the Test Case Name, username, email and expected result.
	$poster_name = htmlspecialchars($user_info['username']);
	$poster_email = htmlspecialchars($user_info['email']);

	$runOptions = array(
		'id' => empty($run_id) ? 0 : $run_id,
		'id_case' => empty($case_id) ? 0 : $case_id,
		'result_achieved' => $_POST['result'],
		'feedback' => $_POST['feedback'],
		'id_bug' => empty($id_bug) ? 0 : $id_bug,
	);
	$posterOptions = array();

	// Only consider marking as editing if they have edited the subject, message or icon.
	if ((isset($_POST['result']) && $_POST['result'] != $row['result_achieved']) || (isset($_POST['feedback']) && $_POST['feedback'] != $row['feedback']) || (isset($_POST['id_bug']) && $_POST['id_bug'] != $row['id_bug']))
	{
			$runOptions['modify_time'] = time();
			$runOptions['modified_by'] = $user_info['name'];
	}
	modifyRun($runOptions, $posterOptions);

	// If we didn't change anything this time but had before put back the old info.
	if (!isset($runOptions['modify_time']) && !empty($row['modified_time']))
	{
		$runOptions['modify_time'] = $row['modified_time'];
		$runOptions['modified_by'] = $row['modified_by'];
	}
	redirectexit('action=testsuite;project='. $project_id .';suite='. $suite_id .';case='. $case_id);
}

function RunValidator()
{
	global $context, $modSettings, $smcFunc, $txt;

	if (isset($_POST['message']) || isset($_POST['feedback']))
	{
		// Validate inputs.
		if (empty($context['post_error']))
		{
			if($_POST['result'] == 'select')
				$context['post_error']['no_result'] = true;
			if (htmltrim__recursive(htmlspecialchars__recursive($_REQUEST['feedback'])) == '')
				$context['post_error']['no_feedback'] = true;
			if ($smcFunc['strlen']($_REQUEST['feedback']) > $modSettings['max_messageLength'])
				$context['post_error']['long_message'] = true;
		}
		else
		{
			if (!isset($_REQUEST['result']))
				$_REQUEST['result'] = '';
			if (!isset($_REQUEST['feedback']))
				$_REQUEST['feedback'] = '';
		}

		// Set up the inputs for the form.
		$feedback = $smcFunc['htmlspecialchars']($_REQUEST['feedback'], ENT_QUOTES);

		// Any errors occurred?
		if (!empty($context['post_error']))
		{
			loadLanguage('Errors');

			$context['error_type'] = 'minor';

			$context['post_error']['feedback'] = array();
			foreach ($context['post_error'] as $post_error => $dummy)
			{
				if ($post_error == 'feedback')
					continue;

				if ($post_error == 'long_message')
					$txt['error_' . $post_error] = sprintf($txt['error_' . $post_error], $modSettings['max_messageLength']);

				$context['post_error']['feedback'][] = $txt['error_' . $post_error];

				$context['error_type'] = 'serious';
			}
		}
		
		$context['result_achieved'] = $_REQUEST['result'];
		$context['feedback'] = str_replace(array('"', '<', '>', '&nbsp;'), array('&quot;', '&lt;', '&gt;', ' '), $feedback);
	
		if(!empty($id_bug))
		$context['id_bug'] = $id_bug;

		// No check is needed, since nothing is really posted.
		checkSubmitOnce('free');
	}
}

?>